<!--
 /**
 * Date: 2022-03-23 10:52
 * Desc: newBaseInfo 新增实物产品--基本信息
 */
-->
<template>
  <div class="new-base-info">
    <zm-form :model="form" :rules="rulesForm" ref="formRef" label-position="right" label-width="120px">
      <zm-form-item label="商品" prop="isMulti">
        <zm-data-radio :list="storeList" v-model="form.isMulti" @change="changIsMulti"></zm-data-radio>
      </zm-form-item>
      <div :class="+form.isMulti === 0 ? 'new-base-info__single-store' : ''">
        <zm-form-item label="产品名称" prop="name">
          <zm-input v-model="form.name" class="w300"></zm-input>
        </zm-form-item>
        <zm-form-item label="产品类目">
          <el-cascader class="w300" v-model="category" :options="categoryList" :show-all-levels="false" :props="{value: 'id',label:'name',multiple: true}" :clearable="true" collapse-tags></el-cascader>
        </zm-form-item>
        <template v-if="+form.isMulti === 0">
          <zm-form-item label="品牌">
            <zm-input v-model="form.brand" class="w300"></zm-input>
          </zm-form-item>
          <zm-form-item label="图片">
            <zm-image-upload v-model="form.image" :limit="1"></zm-image-upload>
          </zm-form-item>
          <zm-form-item label="产地">
            <zm-input class="w300" v-model="form.origin"></zm-input>
          </zm-form-item>
          <zm-form-item label="规格">
            <zm-input class="w300" v-model="form.specification"></zm-input>
          </zm-form-item>
          <zm-form-item label="单位">
            <zm-input class="w300" v-model="form.unit"></zm-input>
          </zm-form-item>
          <zm-form-item label="保质期">
            <div class="new-base-info__counter">
              <el-input-number v-model="form.shelfLife" class="w260" :precision="0" :min="0" :controls="false"></el-input-number>
              <span class="new-base-info__append">月</span>
            </div>
          </zm-form-item>
        </template>

        <div v-else class="mb10 pl25">
          <div class="mb10">
            <span class="pr10">已关联{{form.productListName.length}}个产品</span>
            <zm-button @click="onSelectProduct">选择产品</zm-button>
          </div>
          <zm-table-data ref="tableRef" :columns="column" :data="form.productListName" :table-params="tableParams" mutilple @selection-change="handleSelect"></zm-table-data>
          <div class="mt10 row-bettow">
            <zm-button @click="batchDelete">-批量移除</zm-button>
            <div class="row-bettow" v-if="form.productListName.length">
              <span>成本价总额 : ￥{{allCostPrice}} &nbsp;</span>
              <span>最低销售单价总额 : ￥{{allMinSalePrice}}</span>
            </div>
          </div>
        </div>

        <zm-form-item label="运费">
          <div class="new-base-info__counter">
            <el-input-number v-model="form.deliveryMoney" class="w260" :precision="2" :min="0" :controls="false"></el-input-number>
            <span class="new-base-info__append">元</span>
          </div>
        </zm-form-item>
        <zm-form-item label="成本价" prop="costPrice">
          <div class="new-base-info__counter">
            <el-input-number v-model="form.costPrice" class="w260" :precision="2" :min="0" :controls="false"></el-input-number>
            <span class="new-base-info__append">元</span>
          </div>
        </zm-form-item>
        <zm-form-item label="最低销售单价" prop="minSalePrice">
          <div class="new-base-info__counter">
            <el-input-number v-model="form.minSalePrice" class="w260" :precision="2" :min="0" :controls="false"></el-input-number>
            <span class="new-base-info__append">元</span>
          </div>
        </zm-form-item>
        <zm-form-item label="产品可售部门">
          <zm-data-radio v-model="form.isApartment" :list="apartmentRadio" />
          <zm-form-item label="" v-if="+form.isApartment === 2" prop="companyId">
          <zm-data-select @change="companyChange" v-model="form.companyId" api="getCompanyList" label-name="companyName" value-key="companyId" placeholder="请选择公司" class="w300 "></zm-data-select>
        </zm-form-item>
          <zm-form-item class="mt10 mb0" v-if="+form.isApartment === 2 && form.companyId&&apartmentList.length">
            <tree-select ref="treeSelect2" :is-checkbox="true" out-class="w300" v-model="form.apartmentList" :tree="apartmentList" :tree-props="{ label: 'name', valueKey: 'value' }" placeholder="请选择指定部门"></tree-select>
          </zm-form-item>
        </zm-form-item>
        <zm-form-item label="使用规则">
          <zm-input type="textarea" :rows="10" show-word-limit :maxlength="1000" class="w300" v-model="form.usageRules" placeholder="请输入使用规则"></zm-input>
        </zm-form-item>
        <zm-form-item label="产品备注">
          <zm-input type="textarea" :rows="4" show-word-limit :maxlength="200" class="w300" v-model="form.remark" placeholder="请输入产品备注"></zm-input>
        </zm-form-item>
      </div>
    </zm-form>

    <select-shiwu-product v-if="selectProductParams.visible" v-model="selectProductParams.visible" :product-info="form.productListName" @after-select="afterSelect" is-multi="0"></select-shiwu-product>
  </div>
</template>
<script>
import publicApis from '@/api/src/public'
import { getProductInfo } from '@/api/src/productDraft'
import ZmImageUpload from '@/components/ZmUpload/components/ImageUpload.vue'
import { shiwuProductColumns } from './const.js'
import zmTableMixin from '@/mixins/zmTableMixin'
import SelectShiwuProduct from '../selectShiwuProduct/index.vue'
import TreeSelect from '@/components/TreeSelect'

import { accAdd, getArrDifference } from '@/utils/num'

export default {
  name: 'NewBaseInfo',
  components: { ZmImageUpload, SelectShiwuProduct, TreeSelect },
  mixins: [zmTableMixin],
  props: {
    obj: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data () {
    return {
      categoryList: [], // 产品类目下拉
      apartmentList: [], // 指定部门下拉
      storeList: [
        {
          value: '0',
          name: '单个商品'
        },
        {
          value: '1',
          name: '组合商品'
        }
      ],

      apartmentRadio: [
        {
          value: '1',
          name: '全部部门'
        },
        {
          value: '2',
          name: '指定部门'
        }
      ],
      form: {
        companyId: '',
        isMulti: '0', // 商品类型 0 单 1 复合
        name: '', // 产品名称
        category: [], // 产品类目
        // mainCategory: '', // 一级类目Id
        // childCategory: '', // 二级类目Id
        productListName: [], // 关联产品列表
        // productListName: [], // 已关联产品数组
        brand: '', // 品牌名称
        image: '', // 图片
        origin: '', // 产地
        specification: '', // 规格
        unit: '', // 单位
        shelfLife: undefined, // 保质期(月)
        deliveryMoney: undefined, // 运费(元)
        costPrice: undefined, // 成本价(元)
        minSalePrice: undefined, // 最低销售单价(元)
        isApartment: '2', // 产品可售部门类型 (1全部 2指定)
        apartmentList: '', // 指定产品可售部门 逗号分隔
        usageRules: '', // 使用规则
        remark: '' // 产品备注
      },
      initForm: {
        name: '', // 产品名称
        category: [], // 产品类目
        // mainCategory: '', // 一级类目Id
        // childCategory: '', // 二级类目Id
        brand: '', // 品牌名称
        productListName: [], // 关联产品列表
        // productListName: [], // 已关联产品数组
        image: '', // 图片
        origin: '', // 产地
        specification: '', // 规格
        unit: '', // 单位
        shelfLife: undefined, // 保质期(月)
        deliveryMoney: undefined, // 运费(元)
        costPrice: undefined, // 成本价(元)
        minSalePrice: undefined, // 最低销售单价(元)
        isApartment: '2', // 产品可售部门类型 (1全部 2指定)
        apartmentList: '', // 指定产品可售部门 逗号分隔
        usageRules: '', // 使用规则
        remark: '' // 产品备注
      },
      rulesForm: {
        isMulti: { required: true, message: '请选择商品类型', triggle: 'change' },
        name: { required: true, message: '请填写产品名称', triggle: 'blur' },
        costPrice: { required: true, message: '请输入成本价', type: 'number', triggle: 'blur' },
        minSalePrice: { required: true, message: '请输入最低销售单价', type: 'number', triggle: 'blur' }
      },
      selectProductParams: {
        visible: false
      },
      selectList: [] // 勾选的已关联产品
    }
  },
  computed: {
    column () {
      return shiwuProductColumns(this)
    },
    allCostPrice () {
      let allCostPrice = 0
      this.form.productListName.length !== 0 ? this.form.productListName.forEach(({ costPrice }) => {
        // accAdd 小数计算加法
        allCostPrice = accAdd(allCostPrice, +costPrice)
      }) : allCostPrice = undefined
      return allCostPrice
    },
    allMinSalePrice () {
      let allMinSalePrice = 0
      this.form.productListName.length !== 0 ? this.form.productListName.forEach(({ minSalePrice }) => {
        allMinSalePrice = accAdd(allMinSalePrice, +minSalePrice)
      }) : allMinSalePrice = undefined
      return allMinSalePrice
    },
    allDeliveryMoney () {
      let allDeliveryMoney = 0
      this.form.productListName.length !== 0 ? this.form.productListName.forEach(({ deliveryMoney }) => {
        allDeliveryMoney = accAdd(allDeliveryMoney, +deliveryMoney)
      }) : allDeliveryMoney = undefined
      return allDeliveryMoney
    },
    category: {
      get () {
        if (this.form.category && this.form.category.length > 0) {
          const map = this.form.category.map(item => {
            return [item.mainCategory, item.childCategory]
          })
          return map
        } else {
          return []
        }
      },
      set (v) {
        const category = v.map(item => { return {mainCategory: item[0], childCategory: item[1]} })
        this.$set(this.form, 'category', category)
      }

    }
  },
  watch: {
    'form.productListName': {
      handler (newVal, oldValue) {
        if (+this.form.isMulti === 1) {
          console.log(13221321)
          console.log(this.form.deliveryMoney)
          this.$set(this.form, 'deliveryMoney', this.allDeliveryMoney)
          console.log(this.form.deliveryMoney)
          this.$set(this.form, 'costPrice', this.allCostPrice)
          this.$set(this.form, 'minSalePrice', this.allMinSalePrice)
        }
      }
    }
  },
  async created () {
    await this.init()
  },
  mounted () { },
  methods: {
    async init () {
      this.categoryList = await publicApis.getProductCategoryList()

      if (this.obj.id) {
        const _res = await getProductInfo({ id: this.obj.id })
        this.form.isMulti = _res.isMulti
        this.form = JSON.parse(JSON.stringify(_res))
        this.companyChange()
        if (!this.form.hasOwnProperty('productListName')) {
          // console.log('-------------------------------')
          this.$set(this.form, 'productListName', [])
          // this.form.productListName = []
        }
      }
    },
    async companyChange() {
      this.apartmentList = []
      this.apartmentList = await publicApis.apartmentList({
        companyId: this.form.companyId
      })
    },
    afterSelect (list) {
      this.form.productListName = JSON.parse(JSON.stringify(list))
    },
    handleSelect (selectList) {
      this.selectList = selectList
    },
    batchDelete () {
      // getArrDifference 获取两个数组之间的不同元素并返回其组成的新数组
      this.form.productListName = getArrDifference(this.form.productListName, this.selectList)
      this.selectList = []
      this.$refs.tableRef.clearSelection()
    },
    changIsMulti (val) {
      this.form = Object.assign({}, this.form, { ...this.initForm, isMulti: val })
      this.$nextTick(() => {
        this.$refs.formRef.clearValidate()
      })
    },
    onSelectProduct () {
      this.selectProductParams = {
        visible: true
      }
    },
    async waitSubmit () {
      try {
        // this.$set(this.form, 'childCategory', this.form.category[1])
        // this.$set(this.form, 'mainCategory', this.form.category[0])
        // this.from.category = JSON.stringify(this.form.category)

        console.log('123213123', 'this.form.productListName')
        if (this.form.productListName && this.form.productListName.length !== 0) {
          const ids = this.form.productListName.map(item => item.id)
          this.$set(this.form, 'productList', ids.join(','))
        }

        await this.$refs.formRef.validate()
      } catch (err) {
        console.log(err, '验证失败')
      }
    },
    onDel (row, index) {
      this.tableParams.selectList = this.tableParams.selectList.filter(item => {
        return item.id !== row.id
      })
      this.form.productListName.splice(index, 1)
    }
  }
}
</script>
<style lang="scss" scoped>
.new-base-info {
  margin-top: 10px;
  &__single-store {
    margin-left: 32%;
  }
  &__counter {
    display: flex;
  }
  &__append {
    display: inline-block;
    height: 32px;
    width: 35px;
    background: #f5f7fa;
    border: 1px solid #dcdfe6;
    border-left: unset;
    border-radius: 0 4px 4px 0;
    color: #909399;
    text-align: center;
  }
}
</style>
